package com.njit.office.controller;

import com.njit.office.dataobject.LoginUser;
import com.njit.office.model.Result;
import com.njit.office.service.FileService;
import com.njit.office.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;


@Controller
@RequestMapping("/api/users/")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private FileService fileService;


    @PostMapping("update")
    @ResponseBody
    public Result updateUserInfoWithAvatar(@ModelAttribute("userForm") LoginUser loginUser, @RequestParam("file")MultipartFile file){

        //存储头像
        try {
            if (file != null) {
                InputStream inputStream = file.getInputStream();
                Result result = fileService.saveFile(inputStream, file.getOriginalFilename());
                String fileId = (String) result.getData();
                loginUser.setAvatar(fileId);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //更新用户信息
       return userService.update(loginUser);
    }

    @PostMapping("updateUserInfo")
    @ResponseBody
    public Result updateUserInfoWithAvatar(@ModelAttribute("userForm") LoginUser loginUser){
        //更新用户信息
        return userService.update(loginUser);
    }

    @GetMapping("updateView")
    public String updateUserInfo(Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("userId") == null) {
            return "main::userInfo";
        }
        String userId = (String) session.getAttribute("userId");
        LoginUser loginUser = userService.getUserWithId(userId);
        model.addAttribute("user", loginUser);
        return "main::userInfo";
    }



}
